Function Annotations

PEP 3107 introduced a syntax for adding arbitrary metadata annotations to Python functions.
Function annotations, both for parameters and return values, are completely optional.

Syntax

Annotations for parameters take the form of optional expressions written after the parameter name:

def foo(a: expression, b: expression = 5):
    ...

The function’s return value is annotated by using the literal -> after the function definition followed by the Python expression:

def sum() -> expression:
    ...

The expression for the annotations will be evaluated when the function definition is executed.

def func(name: str, age: int) -> str:
    return_str = f'{name} is {age} years old'
    return return_str

Accessing Function Annotations

Once compiled, function annotations are retrieved by using the __annotations__ attribute which returns a mutable dictionary.

print(func.__annotations__)
{'name': <class 'str'>, 'age': <class 'int'>, 'return': <class 'str'>}